﻿using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Metadata;
using System.Diagnostics;

namespace MySuperSocketServer.Filter.CommandFilter
{
    /// <summary>
    /// 记录执行时间过滤器
    /// </summary>
    public class RecordExecutionTimeCommandFilter : CommandFilterAttribute
    {
        public override void OnCommandExecuting(CommandExecutingContext commandContext)
        {
            Stopwatch sw = commandContext.Session.Items.GetValue<Stopwatch>("RecordExecutionTime");
            if (sw != null)
            {
                sw.Restart();
            }
            else
            {
                sw = new Stopwatch(); sw.Start();
                commandContext.Session.Items["RecordExecutionTime"] = sw;
            }
        }

        public override void OnCommandExecuted(CommandExecutingContext commandContext)
        {
            Stopwatch sw = commandContext.Session.Items.GetValue<Stopwatch>("RecordExecutionTime");
            if (sw != null)
            {
                sw.Stop();
                if (commandContext.Session.Logger.IsInfoEnabled)
                {
                    commandContext.Session.Logger.Info($"SessionID：{commandContext.Session.SessionID} command '{commandContext.CurrentCommand.Name}' took {sw.ElapsedMilliseconds} ms!");
                }
            }
        }
    }
}
